import wepy from 'wepy'
import codeMessage from './codeMessage.js'
import tools from './tools.js'
function getFormData (codeKey, key, value) {
  let fromData = ''
  for (let i = 0; i < value.length; i++) {
    for (let skey in value[i]) {
      if (value[i][skey] && value[i][skey].length !== 0) {
        if (Array.isArray(value[i][skey])) {
          let newArr = value[i][skey]
          for (let ai = 0; ai < newArr.length; ai++) {
            for (let akey in newArr[ai]) {
              fromData += codeKey + '[' + i + '].' + skey + '[' + ai + '].' + encodeURIComponent(akey) + '=' + encodeURIComponent(newArr[ai][akey]) + '&'
            }
          }
        } else {
          fromData += codeKey + '[' + i + '].' + encodeURIComponent(skey) + '=' + encodeURIComponent(value[i][skey]) + '&'
        }
      }
    }
  }
  return fromData
}
/**
 * [ajax 统一请求方法]
 * @param  {[type]}  item [description]
 * @return {Boolean}      [description]
 */

const fetch = async(
  {url = '', headers = {}, methods = 'GET', data = {}, transformRequest = '' }
) => {
  // 增强体验：加载中
  wx.showNavigationBarLoading()
  // token 
  const header = tools.getHeaders() || {}
  if (['POST','PUT', 'DELETE'].indexOf(methods) > -1) {
    header['content-type'] = 'application/x-www-form-urlencoded'
    if (typeof data === 'object') {
      transformRequest = function (data) {
        let ret = ''
        for (let key in data) {
          if (Array.isArray(data[key])) {
            if (/(\[|\])/g.exec(JSON.stringify(data[key])).length === 2 && (data[key] + '').indexOf('object') === -1) {
              ret += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
            } else {
              ret += getFormData(key, key, data[key])
            }
          } else {
            ret += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
          }
        }
        return ret
      } (data)
    }
  }
  // 构造请求体
  const request = {
    url: url + (transformRequest ? ('?' + transformRequest) : ''),
    method: ['GET', 'POST','PUT', 'DELETE'].indexOf(methods) > -1 ? methods : 'GET',
    header: header,
    data: transformRequest ? {} : Object.assign({}, data)
  }
  // 控制台调试日志
  console.log(request)
  // 发起请求
  let res = await wepy.request(request)
  wx.hideNavigationBarLoading()
  console.log(res.data)
  console.log('[SUCCESS]', res.statusCode, res.data)
      // 状态码正常 & 确认有数据
    if (res.data.result === "0") {
      // 成功回调
      return res.data
    } else if (['2101', '2102', '2103', '2104', '2105', '2106', '4000'].indexOf(res.data.result) !== -1) {
      // 删除过时token
      // wepy.removeStorageSync('htxk_token', null)
      // 获取用户信息
      let userInfo = wepy.getStorageSync('htxk_userinfo')
      // 重新登录
      if (userInfo) {
        let login = await wepy.login()
        let relogin = await fetch({
          url: wepy.$appConfig.webOpenBasePath + '/v1/muser/_guest/login',
          data: {
            code: login.code,
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            gender: userInfo.gender
          }
        })
        wepy.setStorageSync('htxk_token', {
          openId: relogin.data.openId,
          token: relogin.data.token,
          userId: relogin.data.userId
        })
        return await fetch({
          url: request.url,
          data: request.data,
          methods: request.methods
        })
      }
    } else {
      // 失败回调：其他情况
      setTimeout(() => {
        wepy.showToast({
          title: res.data.msg || codeMessage[res.data.result] || '操作错误',
          icon: 'none',
          showCancel: false
        })
      })
      throw res.data
    }
}

module.exports = {
  fetch
}